/*********************************************************************
 * File Name: gpioled.c
 * Summary: GPIO subsystem based LED driver with device tree support
 * Description: 
 * This file implements a character device driver for LED control
 * using GPIO subsystem and device tree configuration.
 *
 * Key Features:
 * - Device tree based GPIO configuration
 * - GPIO subsystem API usage
 * - Character device registration with cdev structure
 * - Device class and device node creation
 * - User space to kernel space data transfer
 * - Modern Linux kernel driver architecture
 *
 * Modification History:
 * Version    Author      Date        Changes
 *--------------------------------------------------
 * 1.00.00    yushuang    2025-09-13  Initial release
 *--------------------------------------------------
 ********************************************************************/

 #include <linux/types.h>   /**< ssize_t, size_t, loff_t, __user */
 #include <linux/kernel.h>  /**< printk, memcpy, error codes */
 #include <linux/delay.h>   /**< udelay, mdelay */
 #include <linux/ide.h>     /**< IDE related definitions */
 #include <linux/init.h>    /**< __init, __exit, module_init, module_exit */
 #include <linux/module.h>  /**< THIS_MODULE, MODULE_LICENSE, MODULE_AUTHOR */
 #include <linux/errno.h>   /**< Error codes */
 #include <linux/gpio.h>    /**< GPIO subsystem API */
 #include <linux/cdev.h>    /**< Character device structure */
 #include <linux/device.h>  /**< Device class and device creation */
 #include <linux/of.h>      /**< Device tree support */
 #include <linux/of_address.h> /**< Device tree address functions */
 #include <linux/of_gpio.h> /**< Device tree GPIO functions */
 #include <asm/mach/map.h>  /**< Memory mapping functions */
 #include <asm/uaccess.h>  /**< User space access functions */
 #include <asm/io.h>       /**< I/O access functions */
 #define GPIOLED_CNT      1           /**< Number of device instances */
 #define GPIOLED_NAME     "gpioled"   /**< Device name */
 #define LEDOFF           0           /**< LED off state */
 #define LEDON            1           /**< LED on state */
 
 /* LED Electrical Characteristics:
  * - LED is connected between GPIO and VCC (active low)
  * - GPIO = 0 (low) -> LED ON
  * - GPIO = 1 (high) -> LED OFF
  */
 
 /* Device structure */
 struct gpioled_dev
 {
     dev_t devid;            /* Device number */
     struct cdev cdev;       /* Character device */
     struct class *class;    /* Device class */
     struct device *device;  /* Device instance */
     int major;              /* Major number */
     int minor;              /* Minor number */
     struct device_node *nd; /* Device tree node */
     int led_gpio;           /* GPIO number for LED control */
 };
 
 struct gpioled_dev gpioled = {0};     /* LED device - initialize to zero */
 
 /**
  * @brief Open device function
  * @param inode Inode structure passed to driver
  * @param filp File structure, contains private_data member variable
  *              which is usually set to point to device structure during open
  * @return 0 on success, negative value on failure
  */
 static int led_open(struct inode *inode, struct file *filp)
 {
     filp->private_data = &gpioled; /* Set device pointer */
     return 0;
 }
 
 /**
  * @brief Read data from device
  * @param filp Device file to read from (file descriptor)
  * @param buf Buffer to return data to user space
  * @param cnt Number of bytes to read
  * @param offt Offset relative to file start address
  * @return Number of bytes read, negative value on failure
  */
 static ssize_t led_read(struct file *filp, char __user *buf, size_t cnt, loff_t *offt)
 {
     int retvalue;
     unsigned char ledstat;
     struct gpioled_dev *dev = filp->private_data;
 
     /* Limit read size to prevent buffer overflow */
     if (cnt > 1)
     {
         printk("Read size too large, max 1 byte\n");
         return -EINVAL;
     }
 
     /* Get current LED state from GPIO */
     ledstat = gpio_get_value(dev->led_gpio);
     /* Convert GPIO value to LED state: GPIO=0 means LED ON, GPIO=1 means LED OFF */
     ledstat = (ledstat == 0) ? LEDON : LEDOFF;
 
     retvalue = copy_to_user(buf, &ledstat, cnt);  /* Copy to user space */
     if (retvalue > 0)  /* copy_to_user returns number of bytes NOT copied */
     {
         printk("kernel read failed!\r\n");
         return -EFAULT;
     }
 
     return cnt;  /* Return number of bytes read */
 }
 
 /**
  * @brief Write data to device
  * @param filp Device file representing opened file descriptor
  * @param buf Data to write to device
  * @param cnt Number of bytes to write
  * @param offt Offset relative to file start address
  * @return Number of bytes written, negative value on failure
  */
 static ssize_t led_write(struct file *filp, const char __user *buf, size_t cnt, loff_t *offt)
 {
     int retvalue;
     unsigned char databuf[1];
     unsigned char ledstat;
     struct gpioled_dev *dev = filp->private_data;
 
     /* Limit write size to prevent buffer overflow */
     if (cnt > 1)
     {
         printk("Write size too large, max 1 byte\n");
         return -EINVAL;
     }
 
     retvalue = copy_from_user(databuf, buf, cnt);  /* Copy from user space */
     if (retvalue > 0)  /* copy_from_user returns number of bytes NOT copied */
     {
         printk("kernel write failed!\r\n");
         return -EFAULT;
     }
 
     ledstat = databuf[0];       /* Get LED control value */
 
     if (ledstat == LEDON)
     {
         gpio_set_value(dev->led_gpio, 0);  /* Set GPIO low to turn on LED */
     }
     else if (ledstat == LEDOFF)
     {
         gpio_set_value(dev->led_gpio, 1);  /* Set GPIO high to turn off LED */
     }
     return cnt;  /* Return number of bytes written */
 }
 
 /**
  * @brief Close/release device function
  * @param inode Inode structure
  * @param filp Device file to close (file descriptor)
  * @return 0 on success, negative value on failure
  */
 static int led_release(struct inode *inode, struct file *filp)
 {
     return 0;
 }
 
 /* File operations */
 static struct file_operations gpioled_fops = {
     .owner = THIS_MODULE,
     .open = led_open,
     .read = led_read,
     .write = led_write,
     .release = led_release,
 };
 
 /**
  * @brief Driver initialization function
  * @param None
  * @return None
  */
 static int __init led_init(void)
 {
     int ret = 0;
 
     /* Initialize LED hardware using device tree */
     /* 1. Find device tree node: gpioled */
     gpioled.nd = of_find_node_by_path("/gpioled");
     if (gpioled.nd == NULL)
     {
         printk("gpioled node not found!\r\n");
         return -EINVAL;
     }
     else
     {
         printk("gpioled node found!\r\n");
     }
 
     /* 2. Get GPIO property from device tree, get LED GPIO number */
     gpioled.led_gpio = of_get_named_gpio(gpioled.nd, "led-gpio", 0);
     if (gpioled.led_gpio < 0)
     {
         printk("can't get led-gpio\r\n");
         return -EINVAL;
     }
     printk("led-gpio num = %d\r\n", gpioled.led_gpio);
 
     /* 3. Request GPIO resource - temporarily disabled for testing */
     /*
     ret = gpio_request(gpioled.led_gpio, "led-gpio");
     if (ret < 0)
     {
         printk("can't request led-gpio!\r\n");
         return -EINVAL;
     }
     */
 
     /* 4. Set GPIO as output with high level, LED off by default */
     ret = gpio_direction_output(gpioled.led_gpio, 1);
     if (ret < 0)
     {
         printk("can't set gpio!\r\n");
         /* gpio_free(gpioled.led_gpio); - temporarily disabled */
         return -EINVAL;
     }
 
     /* Register character device driver */
     /* 5. Create device number */
     if (gpioled.major)
     {
         gpioled.devid = MKDEV(gpioled.major, 0);
         register_chrdev_region(gpioled.devid, GPIOLED_CNT, GPIOLED_NAME);
     }
     else
     {
         alloc_chrdev_region(&gpioled.devid, 0, GPIOLED_CNT, GPIOLED_NAME);  /* Allocate device number */
         gpioled.major = MAJOR(gpioled.devid);     /* Get allocated major device number */
         gpioled.minor = MINOR(gpioled.devid);     /* Get allocated minor device number */
     }
     printk("gpioled major=%d,minor=%d\r\n", gpioled.major, gpioled.minor);
 
     /* 6. Initialize character device structure */
     gpioled.cdev.owner = THIS_MODULE;
     cdev_init(&gpioled.cdev, &gpioled_fops);
 
     /* 7. Add character device to kernel */
     ret = cdev_add(&gpioled.cdev, gpioled.devid, GPIOLED_CNT);
     if (ret < 0)
     {
         printk("cdev_add failed!\r\n");
         unregister_chrdev_region(gpioled.devid, GPIOLED_CNT);
         /* gpio_free(gpioled.led_gpio); - temporarily disabled */
         return ret;
     }
 
     /* 8. Create device class */
     gpioled.class = class_create(THIS_MODULE, GPIOLED_NAME);
     if (IS_ERR(gpioled.class))
     {
         printk("class_create failed!\r\n");
         cdev_del(&gpioled.cdev);
         unregister_chrdev_region(gpioled.devid, GPIOLED_CNT);
         /* gpio_free(gpioled.led_gpio); - temporarily disabled */
         return PTR_ERR(gpioled.class);
     }
 
     /* 9. Create device node in /dev/ */
     gpioled.device = device_create(gpioled.class, NULL, gpioled.devid, NULL, GPIOLED_NAME);
     if (IS_ERR(gpioled.device))
     {
         printk("device_create failed!\r\n");
         class_destroy(gpioled.class);
         cdev_del(&gpioled.cdev);
         unregister_chrdev_region(gpioled.devid, GPIOLED_CNT);
         /* gpio_free(gpioled.led_gpio); - temporarily disabled */
         return PTR_ERR(gpioled.device);
     }
     return 0;
 }
 
 /**
  * @brief Driver exit function
  * @param None
  * @return None
  */
 static void __exit led_exit(void)
 {
     /* Free GPIO resource - temporarily disabled for testing */
     /*
     gpio_free(gpioled.led_gpio);
     */
 
     /* Unregister character device driver */
     /* Destroy device node first, then remove cdev */
     if (gpioled.device)
     {
         device_destroy(gpioled.class, gpioled.devid);
     }
 
     if (gpioled.class)
     {
         class_destroy(gpioled.class);
     }
 
     cdev_del(&gpioled.cdev);                     /* Remove cdev from kernel */
     unregister_chrdev_region(gpioled.devid, GPIOLED_CNT);  /* Free device number */
 }
 
 module_init(led_init);
 module_exit(led_exit);
 MODULE_LICENSE("GPL");
 MODULE_AUTHOR("yushuang");
 